# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 量表API
"""

from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
from app.api.scales import bp
from app.models import Scale, ScaleCategory, ScaleQuestion, QuestionOption, ScaleScoringRule, ScalePublisher
from app.models.scale import ScaleTag, ScoringRuleDimension
from app.models.assessment import Assessment, AssessmentAnswer, AssessmentStatus
from app import db
from app.utils.helpers import success_response, error_response
from app.services.scale_service import ScaleService
from datetime import datetime


@bp.route('/', methods=['GET'])
@jwt_required(optional=True)
def get_scales():
    """获取量表列表（只显示系统内置量表且符合会员权限的）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        category_id = request.args.get('category_id', type=int)
        search = request.args.get('search', '').strip()
        is_free = request.args.get('is_free', type=bool)
        
        # 获取用户会员级别
        user_membership_level = 'basic'  # 默认基础级别
        user_id = get_jwt_identity()
        if user_id:
            user_id = int(user_id)  # 转换为整数类型
            from app.models import User
            user = User.query.get(user_id)
            if user:
                user_membership_level = user.get_membership_type()
        
        # 构建查询，只显示系统内置量表
        from sqlalchemy import select
        system_scale_ids = select(ScalePublisher.scale_id).filter_by(
            publisher_type='system',
            status='active'
        )
        
        query = Scale.query.filter(
            Scale.id.in_(system_scale_ids),
            Scale.status == 'PUBLISHED',
            Scale.is_public == True
        )
        
        # 会员级别过滤
        level_priority = {
            'basic': 1,
            'professional': 2, 
            'institution': 3,
            'research': 4
        }
        user_priority = level_priority.get(user_membership_level, 1)
        
        # 只显示用户权限可用的量表
        available_levels = [level for level, priority in level_priority.items() if priority <= user_priority]
        query = query.filter(Scale.min_member_level.in_(available_levels))
        
        if category_id:
            query = query.filter_by(category_id=category_id)
        
        if search:
            query = query.filter(
                Scale.title.contains(search) | 
                Scale.description.contains(search)
            )
        
        if is_free is not None:
            query = query.filter_by(is_free=is_free)
        
        # 分页查询
        scales = query.order_by(Scale.usage_count.desc(), Scale.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        scale_list = []
        for scale in scales.items:
            scale_data = {
                'id': scale.id,
                'title': scale.title,
                'subtitle': scale.subtitle,
                'description': scale.description,
                'category_id': scale.category_id,
                'category_name': scale.category.name if scale.category else None,
                'publisher_name': '系统内置',
                'question_count': scale.question_count,
                'estimated_time': scale.estimated_time,
                'usage_count': scale.usage_count or 0,
                'is_free': scale.is_free,
                'price': scale.price,
                'version': scale.version,
                'author': scale.author,
                'published_at': scale.published_at.isoformat() if scale.published_at else None,
                'min_member_level': scale.min_member_level,
                'can_use': scale.can_use(user_membership_level),
                'is_system': True,
                'can_copy': user_id is not None and scale.can_use(user_membership_level)
            }
            scale_list.append(scale_data)
        
        result = {
            'scales': scale_list,
            'pagination': {
                'page': scales.page,
                'pages': scales.pages,
                'per_page': scales.per_page,
                'total': scales.total,
                'has_next': scales.has_next,
                'has_prev': scales.has_prev
            },
            'user_level': user_membership_level
        }
        
        return success_response('获取量表列表成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取量表列表失败: {str(e)}')
        return error_response('获取量表列表失败')


@bp.route('/<int:scale_id>', methods=['GET'])
@jwt_required(optional=True)
def get_scale_detail(scale_id):
    """获取量表详情"""
    try:
        scale = Scale.query.get(scale_id)
        
        if not scale:
            return error_response('量表不存在', 404)
        
        # 检查访问权限
        user_id = get_jwt_identity()
        can_access = False
        can_edit = False
        
        # 如果是已发布的公开量表，所有人都可以访问
        if scale.status == 'PUBLISHED' and scale.is_public:
            can_access = True
        
        # 如果用户已登录，检查是否是量表的创建者
        if user_id:
            user_id = int(user_id)  # 转换为整数类型
            from app.models import ScalePublisher
            publisher = ScalePublisher.query.filter_by(
                scale_id=scale_id,
                publisher_type='member',
                publisher_id=user_id
            ).first()
            
            if publisher:
                can_access = True
                can_edit = True
        
        if not can_access:
            return error_response('量表不可访问', 403)
        
        # 获取量表问题
        questions = ScaleQuestion.query.filter_by(scale_id=scale_id).order_by(ScaleQuestion.question_number).all()
        
        question_list = []
        for question in questions:
            options = QuestionOption.query.filter_by(question_id=question.id).order_by(QuestionOption.sort_order).all()
            
            option_list = []
            for option in options:
                option_data = {
                    'id': option.id,
                    'option_key': option.option_key,
                    'option_text': option.option_text,
                    'option_value': option.option_value,
                    'sort_order': option.sort_order
                }
                option_list.append(option_data)
            
            question_data = {
                'id': question.id,
                'question_number': question.question_number,
                'question_text': question.question_text,
                'question_type': question.question_type,
                'is_required': question.is_required,
                'options': option_list
            }
            question_list.append(question_data)
        
        # 获取计分规则
        scoring_rules = ScaleScoringRule.query.filter_by(scale_id=scale_id).all()
        
        scoring_rule_list = []
        for rule in scoring_rules:
            rule_data = {
                'id': rule.id,
                'rule_name': rule.rule_name,
                'rule_type': rule.rule_type,
                'calculation_method': rule.calculation_method,
                'min_score': float(rule.min_score) if rule.min_score else None,
                'max_score': float(rule.max_score) if rule.max_score else None,
                'weight': float(rule.weight) if rule.weight else None
            }
            scoring_rule_list.append(rule_data)
        
        # 获取发布者信息
        publisher_info = scale.get_publisher()
        publisher_name = None
        if publisher_info:
            if publisher_info.publisher_type == 'system':
                publisher_name = '系统'
            else:
                publisher_name = f'会员用户 {publisher_info.publisher_id}'
        
        # 获取统计信息
        completed_count = 0
        if scale.status == 'PUBLISHED':
            from app.models import Assessment
            completed_count = Assessment.query.filter_by(
                scale_id=scale_id,
                status='COMPLETED'
            ).count()
        
        scale_data = {
            'id': scale.id,
            'title': scale.title,
            'subtitle': scale.subtitle,
            'description': scale.description,
            'instruction': scale.instruction,
            'category_id': scale.category_id,
            'category_name': scale.category.name if scale.category else None,
            'publisher_name': publisher_name,
            'question_count': scale.question_count,
            'estimated_time': scale.estimated_time,
            'usage_count': scale.usage_count,
            'completed_count': completed_count,
            'is_free': scale.is_free,
            'price': scale.price,
            'version': scale.version,
            'author': scale.author,
            'copyright_info': scale.copyright_info,
            'status': scale.status,
            'is_public': scale.is_public,
            'created_at': scale.created_at.isoformat() if scale.created_at else None,
            'updated_at': scale.updated_at.isoformat() if scale.updated_at else None,
            'published_at': scale.published_at.isoformat() if scale.published_at else None,
            'can_edit': can_edit,
            'questions': question_list,
            'scoring_rules': scoring_rule_list
        }
        
        return success_response('获取量表详情成功', scale_data)
        
    except Exception as e:
        current_app.logger.error(f'获取量表详情失败: {str(e)}')
        return error_response('获取量表详情失败')


@bp.route('/system', methods=['GET'])
@jwt_required()
def get_system_scales():
    """获取系统内置量表列表（用于复制功能）"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        
        # 获取用户会员级别
        user_membership_level = 'basic'
        from app.models import User
        user = User.query.get(user_id)
        if user:
            user_membership_level = user.get_membership_type()
        
        # 构建查询，只显示系统内置量表
        system_scale_ids = db.session.query(ScalePublisher.scale_id).filter_by(
            publisher_type='system',
            status='active'
        ).subquery()
        
        query = Scale.query.filter(
            Scale.id.in_(system_scale_ids),
            Scale.status == 'PUBLISHED',
            Scale.is_public == True
        )
        
        # 会员级别过滤
        level_priority = {
            'basic': 1,
            'professional': 2, 
            'institution': 3,
            'research': 4
        }
        user_priority = level_priority.get(user_membership_level, 1)
        
        # 只显示用户权限可用的量表
        available_levels = [level for level, priority in level_priority.items() if priority <= user_priority]
        query = query.filter(Scale.min_member_level.in_(available_levels))
        
        # 获取所有符合条件的量表
        scales = query.order_by(Scale.usage_count.desc(), Scale.created_at.desc()).all()
        
        scale_list = []
        for scale in scales:
            scale_data = {
                'id': scale.id,
                'title': scale.title,
                'subtitle': scale.subtitle,
                'description': scale.description,
                'category_id': scale.category_id,
                'category_name': scale.category.name if scale.category else None,
                'question_count': scale.question_count,
                'estimated_time': scale.estimated_time,
                'usage_count': scale.usage_count or 0,
                'is_free': scale.is_free,
                'price': scale.price,
                'version': scale.version,
                'author': scale.author,
                'min_member_level': scale.min_member_level,
                'can_copy': scale.can_use(user_membership_level)
            }
            scale_list.append(scale_data)
        
        return success_response('获取系统量表列表成功', scale_list)
        
    except Exception as e:
        current_app.logger.error(f'获取系统量表列表失败: {str(e)}')
        return error_response('获取系统量表列表失败')


@bp.route('/categories', methods=['GET'])
def get_scale_categories():
    """获取量表分类"""
    try:
        categories = ScaleCategory.query.filter_by(status='active').order_by(ScaleCategory.sort_order).all()
        
        category_list = []
        for category in categories:
            category_data = {
                'id': category.id,
                'name': category.name,
                'description': category.description,
                'parent_id': category.parent_id,
                'sort_order': category.sort_order,
                'icon': category.icon,
                'color': category.color
            }
            category_list.append(category_data)
        
        return success_response('获取量表分类成功', {'categories': category_list})
        
    except Exception as e:
        current_app.logger.error(f'获取量表分类失败: {str(e)}')
        return error_response('获取量表分类失败')


@bp.route('/<int:scale_id>/start', methods=['POST'])
@jwt_required()
def start_assessment(scale_id):
    """开始测评"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        scale = Scale.query.get(scale_id)
        
        if not scale:
            return error_response('量表不存在', 404)
        
        if scale.status != 'PUBLISHED' or not scale.is_public:
            return error_response('量表不可访问', 403)
        
        # 检查是否需要付费
        if not scale.is_free:
            # 这里可以添加付费检查逻辑
            pass
        
        # 检查是否有未完成的测评
        from app.models import Assessment
        
        existing_assessment = Assessment.query.filter_by(
            user_id=user_id,
            scale_id=scale_id,
            status='IN_PROGRESS'
        ).first()
        
        if existing_assessment:
            # 返回现有的测评
            assessment_data = {
                'id': existing_assessment.id,
                'scale_id': existing_assessment.scale_id,
                'current_question': existing_assessment.current_question,
                'total_questions': existing_assessment.total_questions,
                'progress_percentage': existing_assessment.progress_percentage,
                'started_at': existing_assessment.started_at.isoformat(),
                'time_spent': existing_assessment.time_spent
            }
            return success_response('继续现有测评', assessment_data)
        
        # 创建新的测评
        assessment = Assessment(
            user_id=user_id,
            scale_id=scale_id,
            status='IN_PROGRESS',
            total_questions=scale.question_count,
            estimated_time=scale.estimated_time * 60 if scale.estimated_time else None,  # 转换为秒
            started_at=datetime.utcnow()
        )
        
        # 设置设备信息
        assessment.user_agent = request.headers.get('User-Agent')
        assessment.ip_address = request.remote_addr
        
        db.session.add(assessment)
        db.session.flush()
        
        # 更新量表使用次数
        scale.usage_count += 1
        
        db.session.commit()
        
        assessment_data = {
            'id': assessment.id,
            'scale_id': assessment.scale_id,
            'current_question': assessment.current_question,
            'total_questions': assessment.total_questions,
            'progress_percentage': assessment.progress_percentage,
            'started_at': assessment.started_at.isoformat(),
            'time_spent': assessment.time_spent
        }
        
        return success_response('开始测评成功', assessment_data)
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'开始测评失败: {str(e)}')
        return error_response('开始测评失败')


@bp.route('/popular', methods=['GET'])
def get_popular_scales():
    """获取热门量表"""
    try:
        limit = request.args.get('limit', 10, type=int)
        
        scales = Scale.query.filter_by(
            status='PUBLISHED',
            is_public=True
        ).order_by(Scale.usage_count.desc()).limit(limit).all()
        
        scale_list = []
        for scale in scales:
            scale_data = {
                'id': scale.id,
                'title': scale.title,
                'subtitle': scale.subtitle,
                'description': scale.description,
                'category_name': scale.category.name if scale.category else None,
                'question_count': scale.question_count,
                'estimated_time': scale.estimated_time,
                'usage_count': scale.usage_count,
                'is_free': scale.is_free,
                'price': scale.price
            }
            scale_list.append(scale_data)
        
        return success_response('获取热门量表成功', {'scales': scale_list})
        
    except Exception as e:
        current_app.logger.error(f'获取热门量表失败: {str(e)}')
        return error_response('获取热门量表失败')


@bp.route('/recommended', methods=['GET'])
@jwt_required(optional=True)
def get_recommended_scales():
    """获取推荐量表"""
    try:
        user_id = get_jwt_identity()
        limit = request.args.get('limit', 10, type=int)
        
        # 基础查询
        query = Scale.query.filter_by(
            status='PUBLISHED',
            is_public=True
        )
        
        if user_id:
            user_id = int(user_id)  # 转换为整数类型
            # 如果用户已登录，可以基于用户历史进行个性化推荐
            # 这里简化为推荐用户未做过的量表
            from app.models import Assessment
            completed_scale_ids = db.session.query(Assessment.scale_id).filter_by(
                user_id=user_id
            ).subquery()
            
            query = query.filter(~Scale.id.in_(completed_scale_ids))
        
        # 按使用次数和创建时间排序
        scales = query.order_by(
            Scale.usage_count.desc(),
            Scale.created_at.desc()
        ).limit(limit).all()
        
        scale_list = []
        for scale in scales:
            scale_data = {
                'id': scale.id,
                'title': scale.title,
                'subtitle': scale.subtitle,
                'description': scale.description,
                'category_name': scale.category.name if scale.category else None,
                'question_count': scale.question_count,
                'estimated_time': scale.estimated_time,
                'usage_count': scale.usage_count,
                'is_free': scale.is_free,
                'price': scale.price
            }
            scale_list.append(scale_data)
        
        return success_response('获取推荐量表成功', {'scales': scale_list})
        
    except Exception as e:
        current_app.logger.error(f'获取推荐量表失败: {str(e)}')
        return error_response('获取推荐量表失败')


# ===== 会员量表管理API =====

@bp.route('/my', methods=['GET'])
@jwt_required()
def get_my_scales():
    """获取我的量表（只显示自己创建的会员量表）"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status')
        search = request.args.get('search', '')
        
        # 查询用户发布的量表（仅限会员发布的）
        from app.models import ScalePublisher
        from sqlalchemy import select
        
        scale_ids_subquery = select(ScalePublisher.scale_id).filter_by(
            publisher_type='member',
            publisher_id=user_id,
            status='active'
        )
        
        query = Scale.query.filter(Scale.id.in_(scale_ids_subquery))
        
        if status:
            query = query.filter_by(status=status.upper())
        
        # 搜索过滤
        if search:
            query = query.filter(Scale.title.contains(search))
        
        scales = query.order_by(Scale.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        scale_list = []
        for scale in scales.items:
            scale_data = {
                'id': scale.id,
                'title': scale.title,
                'subtitle': scale.subtitle,
                'description': scale.description,
                'status': scale.status,
                'category_name': scale.category.name if scale.category else None,
                'question_count': scale.question_count,
                'estimated_time': scale.estimated_time,
                'usage_count': scale.usage_count or 0,
                'is_free': scale.is_free,
                'price': scale.price,
                'version': scale.version,
                'created_at': scale.created_at.isoformat(),
                'published_at': scale.published_at.isoformat() if scale.published_at else None,
                'is_system': False,  # 用户创建的量表肯定不是系统量表
                'can_edit': True,   # 自己的量表都可以编辑
                'can_delete': scale.usage_count == 0 or not scale.usage_count  # 未使用的可以删除
            }
            scale_list.append(scale_data)
        
        result = {
            'scales': scale_list,
            'pagination': {
                'page': scales.page,
                'pages': scales.pages,
                'per_page': scales.per_page,
                'total': scales.total,
                'has_next': scales.has_next,
                'has_prev': scales.has_prev
            }
        }
        
        return success_response('获取我的量表成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取我的量表失败: {str(e)}')
        return error_response('获取我的量表失败')


@bp.route('/my/stats', methods=['GET'])
@jwt_required()
def get_my_scale_stats():
    """获取我的量表统计信息"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        
        # 使用服务层获取统计信息
        from app.services import ScaleService
        stats = ScaleService.get_user_scale_stats(user_id)
        
        if stats is None:
            return error_response('获取统计信息失败')
        
        return success_response('获取统计信息成功', stats)
        
    except Exception as e:
        current_app.logger.error(f'获取量表统计失败: {str(e)}')
        return error_response('获取量表统计失败')


@bp.route('/create', methods=['POST'])
@jwt_required()
def create_scale():
    """创建量表"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        data = request.get_json()
        
        if not data:
            return error_response('请提供量表数据')
        
        # 使用服务层创建量表
        success, message, scale = ScaleService.create_scale(user_id, data)
        
        if not success:
            return error_response(message, 403 if '会员' in message or '权限' in message else 400)
        
        scale_data = {
            'id': scale.id,
            'title': scale.title,
            'status': scale.status,
            'created_at': scale.created_at.isoformat()
        }
        
        return success_response(message, scale_data)
        
    except Exception as e:
        current_app.logger.error(f'创建量表失败: {str(e)}')
        return error_response('创建量表失败')


@bp.route('/<int:scale_id>/edit', methods=['GET', 'PUT'])
@jwt_required()
def edit_scale(scale_id):
    """编辑量表"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        scale = Scale.query.get(scale_id)
        
        if not scale:
            return error_response('量表不存在', 404)
        
        # 检查编辑权限
        if not scale.can_edit(user_id):
            return error_response('您没有权限编辑此量表', 403)
        
        if request.method == 'GET':
            # 获取量表详情用于编辑
            scale_data = {
                'id': scale.id,
                'title': scale.title,
                'subtitle': scale.subtitle,
                'description': scale.description,
                'instruction': scale.instruction,
                'category_id': scale.category_id,
                'status': scale.status,
                'is_public': scale.is_public,
                'is_free': scale.is_free,
                'price': scale.price,
                'version': scale.version,
                'author': scale.author,
                'copyright_info': scale.copyright_info
            }
            
            return success_response('获取量表编辑信息成功', scale_data)
        
        elif request.method == 'PUT':
            # 更新量表
            data = request.get_json()
            
            if not data:
                return error_response('请提供更新数据')
            
            # 更新字段
            if 'title' in data:
                scale.title = data['title']
            if 'subtitle' in data:
                scale.subtitle = data['subtitle']
            if 'description' in data:
                scale.description = data['description']
            if 'instruction' in data:
                scale.instruction = data['instruction']
            if 'category_id' in data:
                scale.category_id = data['category_id']
            if 'is_public' in data:
                scale.is_public = data['is_public']
            if 'is_free' in data:
                scale.is_free = data['is_free']
            if 'price' in data:
                scale.price = data['price']
            if 'author' in data:
                scale.author = data['author']
            if 'copyright_info' in data:
                scale.copyright_info = data['copyright_info']
            
            scale.updated_at = datetime.utcnow()
            
            db.session.commit()
            
            return success_response('量表更新成功')
            
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'编辑量表失败: {str(e)}')
        return error_response('编辑量表失败')


@bp.route('/<int:scale_id>/delete', methods=['DELETE'])
@jwt_required()
def delete_scale(scale_id):
    """删除量表"""
    try:
        current_app.logger.warning(f'=== 开始删除量表 {scale_id} - 新版本代码 ===')
        user_id = int(get_jwt_identity())  # 转换为整数类型
        scale = Scale.query.get(scale_id)
        
        if not scale:
            return error_response('量表不存在', 404)
        
        # 检查删除权限
        if not scale.can_edit(user_id):
            return error_response('您没有权限删除此量表', 403)
        
        # 检查是否有测评记录
        from app.models import Assessment
        assessment_count = Assessment.query.filter_by(scale_id=scale_id).count()
        if assessment_count > 0:
            return error_response('该量表已有测评记录，无法删除', 400)
        
        # 检查是否有测评答案记录（即使没有Assessment记录，也可能有孤立的答案记录）
        from app.models.assessment import AssessmentAnswer
        current_app.logger.warning(f'=== 开始查询量表 {scale_id} 的题目 ===')
        # 获取该量表的所有题目ID
        question_ids = db.session.query(ScaleQuestion.id).filter_by(scale_id=scale_id).all()
        question_ids = [q[0] for q in question_ids]
        current_app.logger.warning(f'=== 查询结果: question_ids={question_ids} ===')
        
        current_app.logger.info(f'删除量表 {scale_id}: 找到 {len(question_ids)} 个题目, question_ids={question_ids}')
        
        if question_ids:
            answer_count = AssessmentAnswer.query.filter(AssessmentAnswer.question_id.in_(question_ids)).count()
            current_app.logger.info(f'删除量表 {scale_id}: 找到 {answer_count} 条答案记录')
            if answer_count > 0:
                # 获取具体的答案记录信息用于调试
                answers = AssessmentAnswer.query.filter(AssessmentAnswer.question_id.in_(question_ids)).all()
                answer_details = [(a.id, a.question_id, a.assessment_id) for a in answers]
                current_app.logger.warning(f'删除量表 {scale_id} 失败: 存在答案记录 {answer_details}')
                return error_response(f'该量表的题目已有 {answer_count} 条答案记录，无法删除。请联系管理员清理数据。', 400)
        else:
            current_app.logger.info(f'删除量表 {scale_id}: 没有题目，检查是否存在孤立的答案记录')
            
            # 检查是否存在引用不存在题目的孤立答案记录
            # 这种情况可能是由于数据不一致导致的
            orphaned_answers = db.session.query(AssessmentAnswer).filter(
                ~AssessmentAnswer.question_id.in_(
                    db.session.query(ScaleQuestion.id)
                )
            ).all()
            
            if orphaned_answers:
                current_app.logger.warning(f'发现 {len(orphaned_answers)} 条孤立答案记录（引用不存在的题目）')
                orphaned_details = [(a.id, a.question_id, a.assessment_id) for a in orphaned_answers]
                current_app.logger.warning(f'孤立答案记录详情: {orphaned_details}')
                
                # 对于没有题目的量表，如果存在孤立答案记录，我们可以选择清理这些记录
                # 但为了安全起见，先记录日志并提示管理员
                return error_response(f'发现 {len(orphaned_answers)} 条孤立的答案记录（引用不存在的题目），请联系管理员清理数据库。', 400)
            else:
                current_app.logger.info(f'删除量表 {scale_id}: 没有题目，也没有孤立答案记录，可以安全删除')
        
        db.session.delete(scale)
        db.session.commit()
        
        return success_response('量表删除成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'删除量表失败: {str(e)}')
        return error_response('删除量表失败')


# ===== 量表题目管理API =====

@bp.route('/<int:scale_id>/questions', methods=['GET', 'POST'])
@jwt_required()
def manage_scale_questions(scale_id):
    """管理量表题目"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        current_app.logger.info(f'管理量表题目请求: scale_id={scale_id}, user_id={user_id}, method={request.method}')
        
        scale = Scale.query.get(scale_id)
        
        if not scale:
            current_app.logger.warning(f'量表不存在: scale_id={scale_id}')
            return error_response('量表不存在', 404)
        
        current_app.logger.info(f'量表信息: id={scale.id}, title={scale.title}, publishers={[p.publisher_id for p in scale.publishers]}')
        
        # 检查编辑权限
        can_edit = scale.can_edit(user_id)
        current_app.logger.info(f'权限检查结果: can_edit={can_edit}, user_id={user_id}')
        
        if not can_edit:
            current_app.logger.warning(f'用户无权限编辑量表: user_id={user_id}, scale_id={scale_id}')
            return error_response('您没有权限编辑此量表', 403)
        
        if request.method == 'GET':
            # 获取量表题目列表
            questions = ScaleQuestion.query.filter_by(scale_id=scale_id).order_by(ScaleQuestion.question_number).all()
            
            question_list = []
            for question in questions:
                options = QuestionOption.query.filter_by(question_id=question.id).order_by(QuestionOption.sort_order).all()
                
                option_list = []
                for option in options:
                    option_data = {
                        'id': option.id,
                        'option_key': option.option_key,
                        'option_text': option.option_text,
                        'option_value': option.option_value,
                        'sort_order': option.sort_order
                    }
                    option_list.append(option_data)
                
                question_data = {
                    'id': question.id,
                    'question_number': question.question_number,
                    'question_text': question.question_text,
                    'question_type': question.question_type,
                    'is_required': question.is_required,
                    'options': option_list
                }
                question_list.append(question_data)
            
            return success_response('获取题目列表成功', {'questions': question_list})
        
        elif request.method == 'POST':
            # 添加新题目
            data = request.get_json()
            current_app.logger.info(f'添加题目数据: {data}')
            
            if not data:
                current_app.logger.warning('未提供题目数据')
                return error_response('请提供题目数据')
            
            # 验证必需字段
            required_fields = ['question_text', 'question_type']
            for field in required_fields:
                if not data.get(field):
                    current_app.logger.warning(f'缺少必需字段: {field}')
                    return error_response(f'{field} 是必需的')
            
            # 获取题目序号（如果前端指定了序号则使用，否则自动计算）
            if 'question_number' in data and data['question_number']:
                question_number = data['question_number']
                # 检查序号是否已存在
                existing_question = ScaleQuestion.query.filter_by(
                    scale_id=scale_id, 
                    question_number=question_number
                ).first()
                if existing_question:
                    current_app.logger.warning(f'题目序号 {question_number} 已存在，自动分配新序号')
                    max_number = db.session.query(db.func.max(ScaleQuestion.question_number)).filter_by(scale_id=scale_id).scalar() or 0
                    question_number = max_number + 1
            else:
                max_number = db.session.query(db.func.max(ScaleQuestion.question_number)).filter_by(scale_id=scale_id).scalar() or 0
                question_number = max_number + 1
            
            # 创建题目
            question = ScaleQuestion(
                scale_id=scale_id,
                question_number=question_number,
                question_text=data['question_text'],
                question_type=data['question_type'],
                is_required=data.get('is_required', True)
            )
            
            try:
                db.session.add(question)
                db.session.flush()
                
                # 添加选项（如果有）
                options = data.get('options', [])
                for i, option_data in enumerate(options):
                    option = QuestionOption(
                        question_id=question.id,
                        option_key=option_data.get('option_key', chr(65 + i)),  # A, B, C...
                        option_text=option_data['option_text'],
                        option_value=option_data.get('option_value', i + 1),
                        sort_order=i + 1
                    )
                    db.session.add(option)
                
                # 提交当前题目后重新计算题目数量
                db.session.flush()  # 确保当前题目已经添加到数据库
                actual_count = ScaleQuestion.query.filter_by(scale_id=scale_id).count()
                scale.question_count = actual_count
                scale.updated_at = datetime.utcnow()
                
                db.session.commit()
                
                question_data = {
                    'id': question.id,
                    'question_number': question.question_number,
                    'question_text': question.question_text,
                    'question_type': question.question_type,
                    'is_required': question.is_required
                }
                
                return success_response('题目添加成功', question_data)
                
            except Exception as e:
                db.session.rollback()
                error_msg = str(e)
                current_app.logger.error(f'添加题目时数据库错误: {error_msg}', exc_info=True)
                
                # 检查是否是重复键错误
                if 'Duplicate entry' in error_msg and 'uk_scale_question' in error_msg:
                    current_app.logger.warning(f'检测到重复键错误，尝试重新分配序号')
                    # 重新分配序号并重试
                    max_number = db.session.query(db.func.max(ScaleQuestion.question_number)).filter_by(scale_id=scale_id).scalar() or 0
                    question.question_number = max_number + 1
                    
                    try:
                        db.session.add(question)
                        db.session.flush()
                        
                        # 重新添加选项
                        options = data.get('options', [])
                        for i, option_data in enumerate(options):
                            option = QuestionOption(
                                question_id=question.id,
                                option_key=option_data.get('option_key', chr(65 + i)),
                                option_text=option_data['option_text'],
                                option_value=option_data.get('option_value', i + 1),
                                sort_order=i + 1
                            )
                            db.session.add(option)
                        
                        actual_count = ScaleQuestion.query.filter_by(scale_id=scale_id).count()
                        scale.question_count = actual_count
                        scale.updated_at = datetime.utcnow()
                        
                        db.session.commit()
                        
                        question_data = {
                            'id': question.id,
                            'question_number': question.question_number,
                            'question_text': question.question_text,
                            'question_type': question.question_type,
                            'is_required': question.is_required
                        }
                        
                        return success_response('题目添加成功', question_data)
                        
                    except Exception as retry_error:
                        db.session.rollback()
                        current_app.logger.error(f'重试添加题目失败: {str(retry_error)}', exc_info=True)
                        return error_response('添加题目失败，请稍后重试')
                else:
                    return error_response('添加题目失败，请稍后重试')
            
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'管理量表题目失败: {str(e)}', exc_info=True)
        return error_response('管理量表题目失败')


@bp.route('/<int:scale_id>/questions/<int:question_id>', methods=['GET', 'PUT', 'DELETE'])
@jwt_required()
def manage_specific_question(scale_id, question_id):
    """管理特定题目"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        scale = Scale.query.get(scale_id)
        
        if not scale:
            return error_response('量表不存在', 404)
        
        # 检查编辑权限
        if not scale.can_edit(user_id):
            return error_response('您没有权限编辑此量表', 403)
        
        question = ScaleQuestion.query.filter_by(id=question_id, scale_id=scale_id).first()
        if not question:
            return error_response('题目不存在', 404)
        
        if request.method == 'GET':
            # 获取题目详情
            options = QuestionOption.query.filter_by(question_id=question_id).order_by(QuestionOption.sort_order).all()
            
            option_list = []
            for option in options:
                option_data = {
                    'id': option.id,
                    'option_key': option.option_key,
                    'option_text': option.option_text,
                    'option_value': option.option_value,
                    'sort_order': option.sort_order
                }
                option_list.append(option_data)
            
            question_data = {
                'id': question.id,
                'question_number': question.question_number,
                'question_text': question.question_text,
                'question_type': question.question_type,
                'is_required': question.is_required,
                'options': option_list
            }
            
            return success_response('获取题目详情成功', question_data)
        
        elif request.method == 'PUT':
            # 更新题目
            data = request.get_json()
            
            if not data:
                return error_response('请提供更新数据')
            
            # 更新题目字段
            if 'question_text' in data:
                question.question_text = data['question_text']
            if 'question_type' in data:
                question.question_type = data['question_type']
            if 'is_required' in data:
                question.is_required = data['is_required']
            
            # 更新选项
            if 'options' in data:
                # 删除现有选项
                QuestionOption.query.filter_by(question_id=question_id).delete()
                
                # 添加新选项
                for i, option_data in enumerate(data['options']):
                    option = QuestionOption(
                        question_id=question_id,
                        option_key=option_data.get('option_key', chr(65 + i)),
                        option_text=option_data['option_text'],
                        option_value=option_data.get('option_value', i + 1),
                        sort_order=i + 1
                    )
                    db.session.add(option)
            
            question.updated_at = datetime.utcnow()
            scale.updated_at = datetime.utcnow()
            
            db.session.commit()
            
            return success_response('题目更新成功')
        
        elif request.method == 'DELETE':
            # 删除题目
            db.session.delete(question)
            
            # 重新排序后续题目
            later_questions = ScaleQuestion.query.filter(
                ScaleQuestion.scale_id == scale_id,
                ScaleQuestion.question_number > question.question_number
            ).all()
            
            for q in later_questions:
                q.question_number -= 1
            
            # 更新量表题目数量
            scale.question_count = max(0, scale.question_count - 1)
            scale.updated_at = datetime.utcnow()
            
            db.session.commit()
            
            return success_response('题目删除成功')
            
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'管理特定题目失败: {str(e)}')
        return error_response('管理特定题目失败')


# ===== 量表发布和预览API =====

@bp.route('/<int:scale_id>/publish', methods=['POST'])
@jwt_required()
def publish_scale(scale_id):
    """发布量表"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        current_app.logger.info(f'用户 {user_id} 尝试发布量表 {scale_id}')
        
        scale = Scale.query.get(scale_id)
        
        if not scale:
            current_app.logger.warning(f'量表不存在: {scale_id}')
            return error_response('量表不存在', 404)
        
        current_app.logger.info(f'量表信息: title={scale.title}, status={scale.status}, question_count={scale.question_count}')
        
        # 检查编辑权限
        if not scale.can_edit(user_id):
            current_app.logger.warning(f'用户 {user_id} 没有权限发布量表 {scale_id}')
            return error_response('您没有权限发布此量表', 403)
        
        # 检查会员权限（只对非系统量表进行检查）
        if not scale.is_system_scale():
            can_create, error_msg = ScaleService.check_member_permission(user_id)
            if not can_create:
                current_app.logger.warning(f'用户 {user_id} 会员权限检查失败: {error_msg}')
                return error_response(error_msg, 400)
        
        # 检查是否可以发布（允许已发布的量表重新发布以更新内容）
        if scale.status == 'ARCHIVED':
            current_app.logger.warning(f'量表 {scale_id} 已归档，不能发布')
            return error_response('已归档的量表不能发布', 400)
        
        # 检查量表基本信息完整性
        if not scale.title or not scale.title.strip():
            current_app.logger.warning(f'量表 {scale_id} 标题为空')
            return error_response('量表标题不能为空', 400)
        
        # 检查量表完整性
        if scale.question_count == 0:
            current_app.logger.warning(f'量表 {scale_id} 没有题目')
            return error_response('量表必须包含至少一个题目才能发布', 400)
        
        # 检查所有题目是否有选项
        questions = ScaleQuestion.query.filter_by(scale_id=scale_id).all()
        current_app.logger.info(f'量表 {scale_id} 实际题目数量: {len(questions)}')
        
        for question in questions:
            current_app.logger.info(f'检查题目 {question.question_number}: type={question.question_type}, text={question.question_text[:50]}...')
            
            if question.question_type in ['single', 'multiple']:
                option_count = QuestionOption.query.filter_by(question_id=question.id).count()
                current_app.logger.info(f'题目 {question.question_number} 选项数量: {option_count}')
                
                if option_count == 0:
                    error_msg = f'题目 {question.question_number} 缺少选项'
                    current_app.logger.warning(error_msg)
                    return error_response(error_msg, 400)
        
        # 发布量表
        current_app.logger.info(f'开始发布量表 {scale_id}')
        scale.status = 'PUBLISHED'
        scale.published_at = datetime.utcnow()
        scale.updated_at = datetime.utcnow()
        
        # 确保有ScalePublisher记录
        from app.models import ScalePublisher
        existing_publisher = ScalePublisher.query.filter_by(
            scale_id=scale_id,
            publisher_type='member',
            publisher_id=user_id
        ).first()
        
        if not existing_publisher:
            publisher = ScalePublisher(
                scale_id=scale_id,
                publisher_type='member',
                publisher_id=user_id,
                publish_time=datetime.utcnow(),
                status='active'
            )
            db.session.add(publisher)
            current_app.logger.info(f'为量表 {scale_id} 创建发布者记录，用户 {user_id}')
        
        db.session.commit()
        current_app.logger.info(f'量表 {scale_id} 发布成功')
        
        return success_response('量表发布成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'发布量表失败: {str(e)}', exc_info=True)
        return error_response(f'发布量表失败: {str(e)}', 500)


@bp.route('/<int:scale_id>/archive', methods=['POST'])
@jwt_required()
def archive_scale(scale_id):
    """归档量表"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        scale = Scale.query.get(scale_id)
        
        if not scale:
            return error_response('量表不存在', 404)
        
        # 检查编辑权限
        from app.models import ScalePublisher
        publisher = ScalePublisher.query.filter_by(
            scale_id=scale_id,
            publisher_type='member',
            publisher_id=user_id
        ).first()
        
        if not publisher:
            return error_response('您没有权限归档此量表', 403)
        
        # 检查是否可以归档
        if scale.status == 'ARCHIVED':
            return error_response('量表已经归档', 400)
        
        if scale.status == 'DRAFT':
            return error_response('草稿状态的量表不能归档', 400)
        
        # 归档量表
        scale.status = 'ARCHIVED'
        scale.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return success_response('量表归档成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'归档量表失败: {str(e)}')
        return error_response('归档量表失败')


@bp.route('/<int:scale_id>/preview', methods=['GET'])
@jwt_required(optional=True)
def preview_scale(scale_id):
    """预览量表"""
    try:
        user_id = int(get_jwt_identity()) if get_jwt_identity() else None  # 转换为整数类型
        current_app.logger.info(f'=== 预览量表 {scale_id}，用户ID: {user_id} ===')
        
        scale = Scale.query.get(scale_id)
        
        if not scale:
            return error_response('量表不存在', 404)
        
        current_app.logger.info(f'量表信息: 标题={scale.title}, 状态={scale.status}, 公开={scale.is_public}')
        
        # 检查权限（创建者或已发布的公开量表）
        if user_id:
            # 如果有用户登录，检查是否为创建者或公开量表
            can_edit = scale.can_edit(user_id)
            current_app.logger.info(f'用户 {user_id} 是否可编辑量表: {can_edit}')
            
            if not can_edit and (scale.status != 'PUBLISHED' or not scale.is_public):
                current_app.logger.warning(f'用户 {user_id} 无权限预览量表 {scale_id}: 不是创建者且量表未公开发布')
                if scale.status != 'PUBLISHED':
                    return error_response('此量表尚未发布，无法预览', 403)
                else:
                    return error_response('此量表未公开，无法预览', 403)
        else:
            # 如果没有用户登录，只能预览已发布的公开量表
            current_app.logger.info(f'匿名用户预览量表 {scale_id}')
            if scale.status != 'PUBLISHED':
                current_app.logger.warning(f'匿名用户无法预览未发布的量表 {scale_id}')
                return error_response('此量表尚未发布，请登录后预览', 403)
            elif not scale.is_public:
                current_app.logger.warning(f'匿名用户无法预览非公开量表 {scale_id}')
                return error_response('此量表未公开，请登录后预览', 403)
        
        # 获取量表详情（与获取量表详情API类似）
        questions = ScaleQuestion.query.filter_by(scale_id=scale_id).order_by(ScaleQuestion.question_number).all()
        
        question_list = []
        for question in questions:
            options = QuestionOption.query.filter_by(question_id=question.id).order_by(QuestionOption.sort_order).all()
            
            option_list = []
            for option in options:
                option_data = {
                    'id': option.id,
                    'option_key': option.option_key,
                    'option_text': option.option_text,
                    'option_value': option.option_value,
                    'sort_order': option.sort_order
                }
                option_list.append(option_data)
            
            question_data = {
                'id': question.id,
                'question_number': question.question_number,
                'question_text': question.question_text,
                'question_type': question.question_type,
                'is_required': question.is_required,
                'options': option_list
            }
            question_list.append(question_data)
        
        scale_data = {
            'id': scale.id,
            'title': scale.title,
            'subtitle': scale.subtitle,
            'description': scale.description,
            'instruction': scale.instruction,
            'category_name': scale.category.name if scale.category else None,
            'question_count': scale.question_count,
            'estimated_time': scale.estimated_time,
            'is_free': scale.is_free,
            'price': scale.price,
            'version': scale.version,
            'author': scale.author,
            'questions': question_list
        }
        
        return success_response('获取量表预览成功', scale_data)
        
    except Exception as e:
        current_app.logger.error(f'预览量表失败: {str(e)}')
        return error_response('预览量表失败')


# ===== 量表分类管理API =====

@bp.route('/categories/manage', methods=['GET', 'POST'])
@jwt_required()
def manage_categories():
    """管理量表分类（需要管理员权限）"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        
        # 检查是否为管理员（这里简化检查，实际应该检查用户角色）
        from app.models import User
        user = User.query.get(user_id)
        if not user or not user.membership or user.membership.plan_type not in ['institution', 'research']:
            return error_response('您没有权限管理分类', 403)
        
        if request.method == 'GET':
            # 获取所有分类（包括非活跃的）
            categories = ScaleCategory.query.order_by(ScaleCategory.sort_order, ScaleCategory.created_at).all()
            
            category_list = []
            for category in categories:
                category_data = {
                    'id': category.id,
                    'name': category.name,
                    'description': category.description,
                    'parent_id': category.parent_id,
                    'sort_order': category.sort_order,
                    'icon': category.icon,
                    'color': category.color,
                    'status': category.status,
                    'created_at': category.created_at.isoformat(),
                    'scale_count': db.session.query(Scale).filter_by(category_id=category.id).count()
                }
                category_list.append(category_data)
            
            return success_response('获取分类列表成功', {'categories': category_list})
            
        elif request.method == 'POST':
            # 创建新分类
            data = request.get_json()
            
            if not data or not data.get('name'):
                return error_response('分类名称不能为空')
            
            # 检查名称是否重复
            existing = ScaleCategory.query.filter_by(name=data['name']).first()
            if existing:
                return error_response('分类名称已存在')
            
            category = ScaleCategory(
                name=data['name'],
                description=data.get('description'),
                parent_id=data.get('parent_id'),
                sort_order=data.get('sort_order', 0),
                icon=data.get('icon'),
                color=data.get('color'),
                status='active'
            )
            
            db.session.add(category)
            db.session.commit()
            
            category_data = {
                'id': category.id,
                'name': category.name,
                'description': category.description,
                'parent_id': category.parent_id,
                'sort_order': category.sort_order,
                'icon': category.icon,
                'color': category.color,
                'status': category.status,
                'created_at': category.created_at.isoformat()
            }
            
            return success_response('分类创建成功', category_data)
            
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'管理分类失败: {str(e)}')
        return error_response('管理分类失败')


@bp.route('/categories/<int:category_id>', methods=['PUT', 'DELETE'])
@jwt_required()
def update_delete_category(category_id):
    """更新或删除分类"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        
        # 检查权限
        from app.models import User
        user = User.query.get(user_id)
        if not user or not user.membership or user.membership.plan_type not in ['institution', 'research']:
            return error_response('您没有权限管理分类', 403)
        
        category = ScaleCategory.query.get(category_id)
        if not category:
            return error_response('分类不存在', 404)
        
        if request.method == 'PUT':
            # 更新分类
            data = request.get_json()
            
            if not data:
                return error_response('请提供更新数据')
            
            # 检查名称冲突
            if 'name' in data and data['name'] != category.name:
                existing = ScaleCategory.query.filter_by(name=data['name']).first()
                if existing:
                    return error_response('分类名称已存在')
            
            # 更新字段
            if 'name' in data:
                category.name = data['name']
            if 'description' in data:
                category.description = data['description']
            if 'parent_id' in data:
                category.parent_id = data['parent_id']
            if 'sort_order' in data:
                category.sort_order = data['sort_order']
            if 'icon' in data:
                category.icon = data['icon']
            if 'color' in data:
                category.color = data['color']
            if 'status' in data:
                category.status = data['status']
            
            category.updated_at = datetime.utcnow()
            
            db.session.commit()
            
            return success_response('分类更新成功')
            
        elif request.method == 'DELETE':
            # 删除分类
            # 检查是否有量表使用此分类
            scale_count = db.session.query(Scale).filter_by(category_id=category_id).count()
            if scale_count > 0:
                return error_response(f'该分类下还有 {scale_count} 个量表，无法删除', 400)
            
            # 检查是否有子分类
            child_count = ScaleCategory.query.filter_by(parent_id=category_id).count()
            if child_count > 0:
                return error_response(f'该分类下还有 {child_count} 个子分类，无法删除', 400)
            
            db.session.delete(category)
            db.session.commit()
            
            return success_response('分类删除成功')
            
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'更新/删除分类失败: {str(e)}')
        return error_response('操作失败')


@bp.route('/categories/batch', methods=['POST'])
@jwt_required()
def batch_update_categories():
    """批量更新分类排序"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        
        # 检查权限
        from app.models import User
        user = User.query.get(user_id)
        if not user or not user.membership or user.membership.plan_type not in ['institution', 'research']:
            return error_response('您没有权限管理分类', 403)
        
        data = request.get_json()
        if not data or 'categories' not in data:
            return error_response('请提供分类数据')
        
        # 更新排序
        for item in data['categories']:
            category_id = item.get('id')
            sort_order = item.get('sort_order')
            
            if category_id and sort_order is not None:
                category = ScaleCategory.query.get(category_id)
                if category:
                    category.sort_order = sort_order
                    category.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return success_response('批量更新成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'批量更新分类失败: {str(e)}')
        return error_response('批量更新失败')


# ===== 系统统计API =====

@bp.route('/stats', methods=['GET'])
def get_scale_stats():
    """获取量表统计信息"""
    try:
        # 总量表数
        total_scales = Scale.query.filter_by(status='PUBLISHED', is_public=True).count()
        
        # 分类统计
        category_stats = db.session.query(
            ScaleCategory.name,
            db.func.count(Scale.id).label('count')
        ).join(Scale, ScaleCategory.id == Scale.category_id)\
         .filter(Scale.status == 'PUBLISHED', Scale.is_public == True)\
         .group_by(ScaleCategory.id, ScaleCategory.name)\
         .order_by(db.func.count(Scale.id).desc())\
         .limit(10).all()
        
        # 热门量表
        popular_scales = Scale.query.filter_by(
            status='PUBLISHED',
            is_public=True
        ).order_by(Scale.usage_count.desc()).limit(5).all()
        
        # 最新量表
        latest_scales = Scale.query.filter_by(
            status='PUBLISHED',
            is_public=True
        ).order_by(Scale.published_at.desc()).limit(5).all()
        
        # 发布者统计
        publisher_stats = db.session.query(
            ScalePublisher.publisher_type,
            db.func.count(Scale.id).label('count')
        ).join(Scale, ScalePublisher.scale_id == Scale.id)\
         .filter(Scale.status == 'PUBLISHED', Scale.is_public == True)\
         .group_by(ScalePublisher.publisher_type).all()
        
        stats = {
            'total_scales': total_scales,
            'category_stats': [{'name': name, 'count': count} for name, count in category_stats],
            'popular_scales': [{
                'id': scale.id,
                'title': scale.title,
                'usage_count': scale.usage_count
            } for scale in popular_scales],
            'latest_scales': [{
                'id': scale.id,
                'title': scale.title,
                'published_at': scale.published_at.isoformat() if scale.published_at else None
            } for scale in latest_scales],
            'publisher_stats': [{'type': ptype, 'count': count} for ptype, count in publisher_stats]
        }
        
        return success_response('获取统计信息成功', stats)
        
    except Exception as e:
        current_app.logger.error(f'获取统计信息失败: {str(e)}')
        return error_response('获取统计信息失败')


# ===== 量表分析API =====

@bp.route('/<int:scale_id>/analytics', methods=['GET'])
@jwt_required()
def get_scale_analytics(scale_id):
    """获取量表分析数据"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        
        # 获取量表
        scale = Scale.query.get(scale_id)
        if not scale:
            return error_response('量表不存在', 404)
        
        # 检查权限 - 只有量表创建者可以查看分析数据
        if not scale.is_published_by_member(user_id):
            return error_response('您没有权限查看此量表的分析数据', 403)
        
        from app.models import Assessment, AssessmentAnswer
        from app.models.assessment import AssessmentScore, AssessmentStatus
        from sqlalchemy import func, extract
        
        # 基础统计
        total_assessments = Assessment.query.filter_by(scale_id=scale_id).count()
        completed_assessments = Assessment.query.filter_by(
            scale_id=scale_id, 
            status=AssessmentStatus.COMPLETED
        ).count()
        
        completion_rate = (completed_assessments / total_assessments * 100) if total_assessments > 0 else 0
        
        # 平均分数 - 通过AssessmentScore计算
        avg_score_result = db.session.query(func.avg(AssessmentScore.raw_score)).join(
            Assessment, AssessmentScore.assessment_id == Assessment.id
        ).filter(
            Assessment.scale_id == scale_id,
            Assessment.status == AssessmentStatus.COMPLETED,
            AssessmentScore.raw_score.isnot(None)
        ).scalar()
        average_score = float(avg_score_result) if avg_score_result else 0
        
        # 活跃用户数
        active_users = db.session.query(func.count(func.distinct(Assessment.user_id))).filter(
            Assessment.scale_id == scale_id
        ).scalar() or 0
        
        # 本月使用次数
        current_month = datetime.utcnow().month
        current_year = datetime.utcnow().year
        monthly_usage = Assessment.query.filter(
            Assessment.scale_id == scale_id,
            extract('month', Assessment.created_at) == current_month,
            extract('year', Assessment.created_at) == current_year
        ).count()
        
        # 使用趋势（最近30天）
        from datetime import timedelta
        end_date = datetime.utcnow().date()
        start_date = end_date - timedelta(days=29)
        
        usage_trend = []
        current_date = start_date
        while current_date <= end_date:
            daily_count = Assessment.query.filter(
                Assessment.scale_id == scale_id,
                func.date(Assessment.created_at) == current_date
            ).count()
            usage_trend.append({
                'date': current_date.strftime('%m-%d'),
                'count': daily_count
            })
            current_date += timedelta(days=1)
        
        # 分数分布
        score_distribution = [0, 0, 0, 0, 0]  # 0-20, 21-40, 41-60, 61-80, 81-100
        completed_with_scores = Assessment.query.filter(
            Assessment.scale_id == scale_id,
            Assessment.status == AssessmentStatus.COMPLETED
        ).all()
        
        for assessment in completed_with_scores:
            # 计算该测评的总分数
            total_score = 0
            if assessment.scores:
                total_score = sum(score.raw_score for score in assessment.scores if score.raw_score)
            
            if total_score <= 20:
                score_distribution[0] += 1
            elif total_score <= 40:
                score_distribution[1] += 1
            elif total_score <= 60:
                score_distribution[2] += 1
            elif total_score <= 80:
                score_distribution[3] += 1
            else:
                score_distribution[4] += 1
        
        # 完成状态统计
        completion_stats = {
            'completed': completed_assessments,
            'in_progress': Assessment.query.filter_by(
                scale_id=scale_id, 
                status=AssessmentStatus.IN_PROGRESS
            ).count(),
            'abandoned': Assessment.query.filter_by(
                scale_id=scale_id, 
                status=AssessmentStatus.ABANDONED
            ).count()
        }
        
        # 周活跃度（周一到周日）
        activity_data = [0] * 7
        for assessment in Assessment.query.filter_by(scale_id=scale_id).all():
            weekday = assessment.created_at.weekday()  # 0=周一, 6=周日
            activity_data[weekday] += 1
        
        # 题目统计
        question_stats = []
        questions = ScaleQuestion.query.filter_by(scale_id=scale_id).order_by(ScaleQuestion.question_number).all()
        for question in questions:
            answer_count = AssessmentAnswer.query.filter_by(question_id=question.id).count()
            total_time = db.session.query(func.sum(AssessmentAnswer.time_spent)).filter_by(
                question_id=question.id
            ).scalar() or 0
            avg_time = (total_time / answer_count) if answer_count > 0 else 0
            
            question_stats.append({
                'question_number': question.question_number,
                'answer_rate': (answer_count / total_assessments * 100) if total_assessments > 0 else 0,
                'avg_time': round(avg_time, 2)
            })
        
        analytics_data = {
            'total_assessments': total_assessments,
            'completed_assessments': completed_assessments,
            'completion_rate': round(completion_rate, 1),
            'average_score': round(average_score, 1),
            'active_users': active_users,
            'monthly_usage': monthly_usage,
            'usage_trend': usage_trend,
            'score_distribution': score_distribution,
            'completion_stats': completion_stats,
            'activity_data': activity_data,
            'question_stats': question_stats,
            'feedback': []  # 暂时为空，后续可以添加用户反馈功能
        }
        
        return success_response('获取分析数据成功', analytics_data)
        
    except Exception as e:
        current_app.logger.error(f'获取量表分析数据失败: {str(e)}')
        return error_response('获取分析数据失败')


@bp.route('/<int:scale_id>/analytics/export', methods=['GET'])
@jwt_required()
def export_scale_analytics(scale_id):
    """导出量表分析报告"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        
        # 获取量表
        scale = Scale.query.get(scale_id)
        if not scale:
            return error_response('量表不存在', 404)
        
        # 检查权限
        if not scale.is_published_by_member(user_id):
            return error_response('您没有权限导出此量表的分析报告', 403)
        
        # 获取分析数据（复用上面的逻辑）
        analytics_response = get_scale_analytics(scale_id)
        if not analytics_response.get_json().get('success'):
            return error_response('获取分析数据失败')
        
        analytics_data = analytics_response.get_json().get('data')
        
        # 生成CSV格式的报告
        import io
        import csv
        
        output = io.StringIO()
        writer = csv.writer(output)
        
        # 写入标题
        writer.writerow(['量表分析报告'])
        writer.writerow(['量表名称', scale.title])
        writer.writerow(['生成时间', datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')])
        writer.writerow([])
        
        # 基础统计
        writer.writerow(['基础统计'])
        writer.writerow(['总使用次数', analytics_data['total_assessments']])
        writer.writerow(['完成次数', analytics_data['completed_assessments']])
        writer.writerow(['完成率', f"{analytics_data['completion_rate']}%"])
        writer.writerow(['平均分数', analytics_data['average_score']])
        writer.writerow(['活跃用户', analytics_data['active_users']])
        writer.writerow(['本月使用', analytics_data['monthly_usage']])
        writer.writerow([])
        
        # 使用趋势
        writer.writerow(['使用趋势（最近30天）'])
        writer.writerow(['日期', '使用次数'])
        for trend in analytics_data['usage_trend']:
            writer.writerow([trend['date'], trend['count']])
        writer.writerow([])
        
        # 分数分布
        writer.writerow(['分数分布'])
        writer.writerow(['分数区间', '人数'])
        score_ranges = ['0-20', '21-40', '41-60', '61-80', '81-100']
        for i, count in enumerate(analytics_data['score_distribution']):
            writer.writerow([score_ranges[i], count])
        writer.writerow([])
        
        # 题目分析
        writer.writerow(['题目分析'])
        writer.writerow(['题目编号', '回答率(%)', '平均用时(秒)'])
        for question in analytics_data['question_stats']:
            writer.writerow([
                question['question_number'],
                f"{question['answer_rate']:.1f}",
                question['avg_time']
            ])
        
        # 准备响应
        output.seek(0)
        
        from flask import Response
        return Response(
            output.getvalue(),
            mimetype='text/csv',
            headers={
                'Content-Disposition': f'attachment; filename="{scale.title}_analytics_report.csv"'
            }
        )
        
    except Exception as e:
        current_app.logger.error(f'导出分析报告失败: {str(e)}')
        return error_response('导出报告失败')


# ===== 量表复制API =====

@bp.route('/copy/<int:source_scale_id>', methods=['POST'])
@jwt_required()
def copy_scale(source_scale_id):
    """复制量表（只能复制系统内置量表）"""
    try:
        user_id = int(get_jwt_identity())  # 转换为整数类型
        
        # 检查会员权限
        can_create, error_msg = ScaleService.check_member_permission(user_id)
        if not can_create:
            return error_response(error_msg, 403)
        
        # 检查量表数量限制
        can_create_more, limit_msg = ScaleService.check_scale_limit(user_id)
        if not can_create_more:
            return error_response(limit_msg, 403)
        
        # 获取源量表
        source_scale = Scale.query.get(source_scale_id)
        if not source_scale:
            return error_response('源量表不存在', 404)
        
        # 检查是否为系统内置量表
        if not source_scale.is_system_scale():
            return error_response('只能复制系统内置量表', 403)
        
        # 检查会员级别是否可以使用此量表
        from app.models import User
        user = User.query.get(user_id)
        user_membership_level = user.get_membership_type()
        
        if not source_scale.can_use(user_membership_level):
            return error_response('您的会员级别无法使用此量表', 403)
        
        data = request.get_json() or {}
        
        # 创建新量表
        new_scale = Scale(
            title=data.get('title', f"{source_scale.title} (副本)"),
            subtitle=data.get('subtitle', source_scale.subtitle),
            description=data.get('description', source_scale.description),
            instruction=data.get('instruction', source_scale.instruction),
            category_id=source_scale.category_id,
            status='DRAFT',  # 复制的量表默认为草稿状态
            is_public=False,  # 会员量表默认私有
            is_free=True,
            price=0.0,
            estimated_time=source_scale.estimated_time,
            version='1.0',  # 重置版本号
            author=data.get('author', user.username or user.email),
            copyright_info=data.get('copyright_info', f"基于 {source_scale.title} 修改"),
            min_member_level='basic'  # 会员创建的量表默认基础会员可用
        )
        
        db.session.add(new_scale)
        db.session.flush()  # 获取新量表的ID
        
        # 创建发布者记录
        publisher = ScalePublisher(
            scale_id=new_scale.id,
            publisher_type='member',
            publisher_id=user_id,
            publish_time=datetime.utcnow(),
            status='active'
        )
        db.session.add(publisher)
        
        # 复制题目和选项
        question_count = 0
        # 使用查询而不是关系属性的 order_by
        source_questions = ScaleQuestion.query.filter_by(scale_id=source_scale_id).order_by(ScaleQuestion.question_number)
        for source_question in source_questions:
            new_question = ScaleQuestion(
                scale_id=new_scale.id,
                question_number=source_question.question_number,
                question_text=source_question.question_text,
                question_type=source_question.question_type,
                is_required=source_question.is_required
            )
            db.session.add(new_question)
            db.session.flush()  # 获取新题目的ID
            
            # 复制选项 - 使用查询而不是关系属性的 order_by
            source_options = QuestionOption.query.filter_by(question_id=source_question.id).order_by(QuestionOption.sort_order)
            for source_option in source_options:
                new_option = QuestionOption(
                    question_id=new_question.id,
                    option_key=source_option.option_key,
                    option_text=source_option.option_text,
                    option_value=source_option.option_value,
                    sort_order=source_option.sort_order
                )
                db.session.add(new_option)
            
            question_count += 1
        
        # 更新题目数量
        new_scale.question_count = question_count
        
        # 复制计分规则
        for source_rule in source_scale.scoring_rules:
            new_rule = ScaleScoringRule(
                scale_id=new_scale.id,
                rule_name=source_rule.rule_name,
                rule_type=source_rule.rule_type,
                calculation_method=source_rule.calculation_method,
                min_score=source_rule.min_score,
                max_score=source_rule.max_score,
                weight=source_rule.weight,
                formula=source_rule.formula
            )
            db.session.add(new_rule)
            db.session.flush()
            
            # 复制维度
            for source_dimension in source_rule.dimensions:
                new_dimension = ScoringRuleDimension(
                    rule_id=new_rule.id,
                    dimension_name=source_dimension.dimension_name,
                    question_numbers=source_dimension.question_numbers,
                    weight=source_dimension.weight
                )
                db.session.add(new_dimension)
        
        # 复制标签
        for source_tag in source_scale.tags:
            new_tag = ScaleTag(
                scale_id=new_scale.id,
                tag_name=source_tag.tag_name,
                tag_color=source_tag.tag_color
            )
            db.session.add(new_tag)
        
        db.session.commit()
        
        current_app.logger.info(f'用户 {user_id} 复制了量表 {source_scale_id}，创建了新量表 {new_scale.id}')
        
        return success_response('复制量表成功', {
            'scale_id': new_scale.id,
            'title': new_scale.title
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'复制量表失败: {str(e)}')
        return error_response('复制量表失败')


@bp.route('/<int:scale_id>/assessments', methods=['GET'])
@jwt_required()
def get_scale_assessments(scale_id):
    """获取量表的测评记录（只有量表创建者可以查看）"""
    try:
        user_id = int(get_jwt_identity())
        
        # 获取量表
        scale = Scale.query.get(scale_id)
        if not scale:
            return error_response('量表不存在', 404)
        
        # 检查权限 - 只有量表创建者可以查看测评记录
        if not scale.is_published_by_member(user_id):
            return error_response('您没有权限查看此量表的测评记录', 403)
        
        from app.models import Assessment, User
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status')
        
        # 构建查询
        query = Assessment.query.filter_by(scale_id=scale_id)
        
        # 按状态筛选
        if status:
            query = query.filter_by(status=status)
        
        # 分页查询
        assessments = query.order_by(Assessment.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 构建返回数据
        assessment_list = []
        for assessment in assessments.items:
            # 计算总分数
            total_score = 0
            if assessment.scores:
                total_score = sum(score.raw_score for score in assessment.scores if score.raw_score)
            
            # 计算用时
            duration = None
            if assessment.completed_at and assessment.created_at:
                duration_seconds = (assessment.completed_at - assessment.created_at).total_seconds()
                if duration_seconds < 60:
                    duration = f"{int(duration_seconds)}秒"
                elif duration_seconds < 3600:
                    duration = f"{int(duration_seconds // 60)}分钟"
                else:
                    duration = f"{int(duration_seconds // 3600)}小时{int((duration_seconds % 3600) // 60)}分钟"
            
            # 获取用户信息
            user = User.query.get(assessment.user_id) if assessment.user_id else None
            
            assessment_data = {
                'id': assessment.id,
                'user_id': assessment.user_id,
                'user_name': user.username if user else '匿名用户',
                'user_email': user.email if user else None,
                'status': assessment.status.value if hasattr(assessment.status, 'value') else str(assessment.status),
                'progress': assessment.progress_percentage or 0,
                'total_score': total_score,
                'duration': duration,
                'created_at': assessment.created_at.isoformat() if assessment.created_at else None,
                'completed_at': assessment.completed_at.isoformat() if assessment.completed_at else None,
                'is_anonymous': assessment.is_anonymous
            }
            assessment_list.append(assessment_data)
        
        # 统计信息
        total_count = Assessment.query.filter_by(scale_id=scale_id).count()
        completed_count = Assessment.query.filter_by(scale_id=scale_id, status=AssessmentStatus.COMPLETED).count()
        
        # 计算平均分数
        from sqlalchemy import func
        from app.models.assessment import AssessmentScore
        avg_score_result = db.session.query(func.avg(AssessmentScore.raw_score)).join(
            Assessment, AssessmentScore.assessment_id == Assessment.id
        ).filter(
            Assessment.scale_id == scale_id,
            Assessment.status == AssessmentStatus.COMPLETED,
            AssessmentScore.raw_score.isnot(None)
        ).scalar()
        average_score = float(avg_score_result) if avg_score_result else 0
        
        # 最近测评时间
        last_assessment = Assessment.query.filter_by(scale_id=scale_id).order_by(
            Assessment.created_at.desc()
        ).first()
        last_assessment_date = last_assessment.created_at.isoformat() if last_assessment else None
        
        stats = {
            'total_count': total_count,
            'completed_count': completed_count,
            'average_score': round(average_score, 1),
            'last_assessment_date': last_assessment_date
        }
        
        # 趋势数据（最近30天）
        from datetime import datetime, timedelta
        end_date = datetime.utcnow().date()
        start_date = end_date - timedelta(days=29)
        
        trend_data = {
            'labels': [],
            'scores': []
        }
        
        # 获取最近30天的完成测评
        completed_assessments = Assessment.query.filter(
            Assessment.scale_id == scale_id,
            Assessment.status == AssessmentStatus.COMPLETED,
            Assessment.completed_at >= start_date
        ).order_by(Assessment.completed_at).all()
        
        # 按日期分组计算平均分数
        daily_scores = {}
        for assessment in completed_assessments:
            date_key = assessment.completed_at.date()
            total_score = sum(score.raw_score for score in assessment.scores if score.raw_score)
            if date_key not in daily_scores:
                daily_scores[date_key] = []
            daily_scores[date_key].append(total_score)
        
        # 生成趋势数据
        current_date = start_date
        while current_date <= end_date:
            trend_data['labels'].append(current_date.strftime('%m-%d'))
            if current_date in daily_scores:
                avg_score = sum(daily_scores[current_date]) / len(daily_scores[current_date])
                trend_data['scores'].append(round(avg_score, 1))
            else:
                trend_data['scores'].append(0)
            current_date += timedelta(days=1)
        
        result = {
            'assessments': assessment_list,
            'stats': stats,
            'trend_data': trend_data,
            'pagination': {
                'page': assessments.page,
                'pages': assessments.pages,
                'per_page': assessments.per_page,
                'total': assessments.total,
                'has_next': assessments.has_next,
                'has_prev': assessments.has_prev
            }
        }
        
        return success_response('获取测评记录成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取量表测评记录失败: {str(e)}')
        return error_response('获取测评记录失败')


# ==================== 会员发布量表相关API ====================

@bp.route('/<int:scale_id>/publish-for-member', methods=['POST'])
@jwt_required()
def publish_scale_for_member(scale_id):
    """发布系统内置量表"""
    try:
        user_id = int(get_jwt_identity())
        
        # 获取量表
        scale = Scale.query.get(scale_id)
        if not scale:
            return error_response('量表不存在', 404)
        
        # 检查是否为系统内置量表
        if not scale.is_system_scale():
            return error_response('只能发布系统内置量表', 400)
        
        # 检查量表是否已发布
        if scale.status != 'PUBLISHED':
            return error_response('量表尚未发布，无法进行会员发布', 400)
        
        from app.models import MemberScalePublication
        
        # 检查是否已经发布过
        existing_publication = MemberScalePublication.query.filter_by(
            member_id=user_id,
            scale_id=scale_id
        ).first()
        
        if existing_publication:
            return error_response('您已经发布过此量表', 400)
        
        # 获取请求数据
        data = request.get_json() or {}
        custom_title = data.get('custom_title', '').strip()
        custom_description = data.get('custom_description', '').strip()
        
        # 生成唯一令牌
        publication_token = MemberScalePublication.generate_token()
        
        # 确保令牌唯一性
        while MemberScalePublication.query.filter_by(publication_token=publication_token).first():
            publication_token = MemberScalePublication.generate_token()
        
        # 创建发布记录
        publication = MemberScalePublication(
            member_id=user_id,
            scale_id=scale_id,
            publication_token=publication_token,
            custom_title=custom_title if custom_title else None,
            custom_description=custom_description if custom_description else None
        )
        
        db.session.add(publication)
        db.session.commit()
        
        # 生成公开访问URL
        base_url = request.host_url.rstrip('/')
        public_url = publication.generate_public_url(base_url)
        
        current_app.logger.info(f'用户 {user_id} 发布了量表 {scale_id}，发布ID: {publication.id}')
        
        result = {
            'id': publication.id,
            'publication_token': publication.publication_token,
            'public_url': public_url,
            'custom_title': publication.custom_title,
            'custom_description': publication.custom_description,
            'created_at': publication.created_at.isoformat()
        }
        
        return success_response('发布成功', result)
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'发布量表失败: {str(e)}')
        return error_response('发布量表失败')


@bp.route('/my-publications', methods=['GET'])
@jwt_required()
def get_my_publications():
    """获取我的发布列表"""
    try:
        user_id = int(get_jwt_identity())
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        from app.models import MemberScalePublication
        
        # 分页查询
        publications = MemberScalePublication.query.filter_by(
            member_id=user_id
        ).order_by(MemberScalePublication.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 构建返回数据
        publication_list = []
        base_url = request.host_url.rstrip('/')
        
        for publication in publications.items:
            scale = publication.scale
            
            publication_data = {
                'id': publication.id,
                'scale': {
                    'id': scale.id,
                    'title': scale.title,
                    'description': scale.description,
                    'question_count': scale.question_count,
                    'estimated_time': scale.estimated_time
                },
                'custom_title': publication.custom_title,
                'custom_description': publication.custom_description,
                'publication_token': publication.publication_token,
                'public_url': publication.generate_public_url(base_url),
                'is_active': publication.is_active,
                'access_count': publication.access_count,
                'assessment_count': publication.assessment_count,
                'last_accessed_at': publication.last_accessed_at.isoformat() if publication.last_accessed_at else None,
                'created_at': publication.created_at.isoformat()
            }
            publication_list.append(publication_data)
        
        result = {
            'publications': publication_list,
            'pagination': {
                'page': publications.page,
                'pages': publications.pages,
                'per_page': publications.per_page,
                'total': publications.total,
                'has_next': publications.has_next,
                'has_prev': publications.has_prev
            }
        }
        
        return success_response('获取发布列表成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取发布列表失败: {str(e)}')
        return error_response('获取发布列表失败')


@bp.route('/publications/<int:publication_id>', methods=['PUT'])
@jwt_required()
def update_publication(publication_id):
    """更新发布信息"""
    try:
        user_id = int(get_jwt_identity())
        
        from app.models import MemberScalePublication
        
        # 获取发布记录
        publication = MemberScalePublication.query.get(publication_id)
        if not publication:
            return error_response('发布记录不存在', 404)
        
        # 检查权限
        if publication.member_id != user_id:
            return error_response('您没有权限修改此发布记录', 403)
        
        # 获取请求数据
        data = request.get_json() or {}
        
        # 更新字段
        if 'custom_title' in data:
            publication.custom_title = data['custom_title'].strip() if data['custom_title'] else None
        
        if 'custom_description' in data:
            publication.custom_description = data['custom_description'].strip() if data['custom_description'] else None
        
        if 'is_active' in data:
            publication.is_active = bool(data['is_active'])
        
        db.session.commit()
        
        current_app.logger.info(f'用户 {user_id} 更新了发布记录 {publication_id}')
        
        result = {
            'id': publication.id,
            'custom_title': publication.custom_title,
            'custom_description': publication.custom_description,
            'is_active': publication.is_active,
            'updated_at': publication.updated_at.isoformat()
        }
        
        return success_response('更新成功', result)
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'更新发布记录失败: {str(e)}')
        return error_response('更新发布记录失败')


@bp.route('/publications/<int:publication_id>', methods=['DELETE'])
@jwt_required()
def delete_publication(publication_id):
    """删除发布记录"""
    try:
        user_id = int(get_jwt_identity())
        
        from app.models import MemberScalePublication
        
        # 获取发布记录
        publication = MemberScalePublication.query.get(publication_id)
        if not publication:
            return error_response('发布记录不存在', 404)
        
        # 检查权限
        if publication.member_id != user_id:
            return error_response('您没有权限删除此发布记录', 403)
        
        db.session.delete(publication)
        db.session.commit()
        
        current_app.logger.info(f'用户 {user_id} 删除了发布记录 {publication_id}')
        
        return success_response('删除成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'删除发布记录失败: {str(e)}')
        return error_response('删除发布记录失败')


@bp.route('/publications/<int:publication_id>/assessments', methods=['GET'])
@jwt_required()
def get_publication_assessments(publication_id):
    """获取发布的测评记录"""
    try:
        user_id = int(get_jwt_identity())
        
        from app.models import MemberScalePublication, Assessment, User
        
        # 获取发布记录
        publication = MemberScalePublication.query.get(publication_id)
        if not publication:
            return error_response('发布记录不存在', 404)
        
        # 检查权限
        if publication.member_id != user_id:
            return error_response('您没有权限查看此发布的测评记录', 403)
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        status = request.args.get('status')
        
        # 构建查询 - 查找通过此发布链接进行的测评
        # 注意：这里需要在Assessment模型中添加publication_id字段来关联
        # 暂时使用scale_id进行查询，后续需要完善
        query = Assessment.query.filter_by(scale_id=publication.scale_id)
        
        # 按状态筛选
        if status:
            query = query.filter_by(status=status)
        
        # 分页查询
        assessments = query.order_by(Assessment.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 构建返回数据
        assessment_list = []
        for assessment in assessments.items:
            # 获取用户基本信息
            user_info = {}
            if assessment.user_id:
                user = User.query.get(assessment.user_id)
                if user and user.basic_info:
                    user_info = {
                        'age': user.basic_info.age,
                        'gender': user.basic_info.gender,
                        'education': user.basic_info.education
                    }
            
            # 计算总分数
            total_score = 0
            if assessment.scores:
                total_score = sum(score.raw_score for score in assessment.scores if score.raw_score)
            
            # 计算用时（秒）
            duration = None
            if assessment.completed_at and assessment.created_at:
                duration = int((assessment.completed_at - assessment.created_at).total_seconds())
            
            assessment_data = {
                'id': assessment.id,
                'user_info': user_info,
                'status': assessment.status.value if hasattr(assessment.status, 'value') else str(assessment.status),
                'total_score': total_score,
                'duration': duration,
                'completed_at': assessment.completed_at.isoformat() if assessment.completed_at else None,
                'created_at': assessment.created_at.isoformat()
            }
            assessment_list.append(assessment_data)
        
        # 统计信息
        total_count = Assessment.query.filter_by(scale_id=publication.scale_id).count()
        completed_count = Assessment.query.filter_by(
            scale_id=publication.scale_id, 
            status=AssessmentStatus.COMPLETED
        ).count()
        
        # 计算平均分数和平均用时
        from sqlalchemy import func
        from app.models.assessment import AssessmentScore
        
        completed_assessments = Assessment.query.filter_by(
            scale_id=publication.scale_id,
            status=AssessmentStatus.COMPLETED
        ).all()
        
        total_scores = []
        durations = []
        
        for assessment in completed_assessments:
            if assessment.scores:
                score = sum(score.raw_score for score in assessment.scores if score.raw_score)
                total_scores.append(score)
            
            if assessment.completed_at and assessment.created_at:
                duration = (assessment.completed_at - assessment.created_at).total_seconds()
                durations.append(duration)
        
        average_score = sum(total_scores) / len(total_scores) if total_scores else 0
        average_duration = sum(durations) / len(durations) if durations else 0
        
        statistics = {
            'total_count': total_count,
            'completed_count': completed_count,
            'average_score': round(average_score, 1),
            'average_duration': int(average_duration)
        }
        
        result = {
            'assessments': assessment_list,
            'pagination': {
                'page': assessments.page,
                'pages': assessments.pages,
                'per_page': assessments.per_page,
                'total': assessments.total,
                'has_next': assessments.has_next,
                'has_prev': assessments.has_prev
            },
            'statistics': statistics
        }
        
        return success_response('获取测评记录成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取发布测评记录失败: {str(e)}')
        return error_response('获取测评记录失败')